<?php
class Imagemodel extends CI_Model {
	function Imagemodel() {
		// Call the Model constructor
		parent::__construct();
	}

	public function resize($filename, $width, $height, $DIR_IMAGE, $HTTPS_IMAGE, $type = "") {
		if (!file_exists($DIR_IMAGE . $filename) || !is_file($DIR_IMAGE . $filename)) {
			return;
		}

		$info = pathinfo($filename);
		$extension = $info['extension'];

		//$old_image = $info['filename'];
		$old_image = $filename;
		//$filename = $old_image;
		
		//$new_image = $filename . '-' . $width . 'x' . $height . '.' . $extension;
		
		$new_image = 'cache/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;

		if (!file_exists($DIR_IMAGE . $new_image) || (filemtime($DIR_IMAGE . $old_image) > filemtime($DIR_IMAGE . $new_image))) {
			$path = '';
			
			$directories = explode('/', dirname(str_replace('../', '', $new_image)));
			
			foreach ($directories as $directory) {
				$path = $path . '/' . $directory;
				
				if (!file_exists($DIR_IMAGE . $path)) {
					@mkdir($DIR_IMAGE . $path, 0777);
				}		
			}

			list($width_orig, $height_orig) = getimagesize($DIR_IMAGE . $old_image);
			
			if ($width_orig != $width || $height_orig != $height) {
				$image = new Myimage($DIR_IMAGE . $old_image);
				$image->resize($width, $height, $type);
				$image->save($DIR_IMAGE . $new_image);
			} else {
				copy($DIR_IMAGE . $old_image, $DIR_IMAGE . $new_image);
			}
			
			/*
			if ($width_orig != $width || $height_orig != $height) {
				$image = new Resizeimage($DIR_IMAGE . $old_image);
				$image->resizeImage($width, $height, 0);
				$image->saveImage($DIR_IMAGE . $new_image);
			} else {
				copy($DIR_IMAGE . $old_image, DIR_IMAGE . $new_image);
			}
			*/
				
			//use Resize Image library
			//$resizeObj = new Resizeimage($DIR_IMAGE . $old_image . '.' . $extension);
			//$resizeObj -> resizeImage($width, $height, 0);
			//$resizeObj -> saveImage($new_image, 100);

			//use Myimage library
			//$image = new Myimage($DIR_IMAGE . $old_image);
			//$image->resize($width, $height);
			//$image->save($DIR_IMAGE . $new_image);
		}

		if (($this->input->server('HTTPS')) && (($this->input->server('HTTPS') == 'on') || ($this->input->server('HTTPS') == '1'))) {
			return $HTTPS_IMAGE . $new_image;
		} else {
			return $HTTPS_IMAGE . $new_image;
		}
	}
}
?>